package com.tencent.qcloud.tim.uikit.modules.chat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.util.AttributeSet;
import android.view.View;

import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.bean.ChatInfo;
import com.manor.common.http.CommonHttpUtil;
import com.manor.common.http.HttpCallback;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.DialogUitl;
import com.manor.common.utils.Gson2Util;
import com.manor.common.utils.KLog;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.StringUtil;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.qcloud.tim.uikit.R;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;
import com.tencent.qcloud.tim.uikit.bean.ChatBgEvent;
import com.tencent.qcloud.tim.uikit.bean.ImRelationBean;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.http.TkHttpConst;
import com.tencent.qcloud.tim.uikit.http.TkHttpUtil;
import com.tencent.qcloud.tim.uikit.modules.chat.base.AbsChatLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatManagerKit;
import com.tencent.qcloud.tim.uikit.modules.group.apply.GroupApplyInfo;
import com.tencent.qcloud.tim.uikit.modules.group.apply.GroupApplyManagerActivity;
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfo;
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfoActivity;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;
import com.tencent.qcloud.tim.uikit.utils.UploadAvatarUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;


public class ChatLayout extends AbsChatLayout implements GroupChatManagerKit.GroupNotifyHandler {

    private GroupInfo mGroupInfo;
    private GroupChatManagerKit mGroupChatManager;
    private C2CChatManagerKit mC2CChatManager;
    private boolean isGroup = false;

    public ChatLayout(Context context) {
        super(context);
    }

    public ChatLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ChatLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setChatInfo(ChatInfo chatInfo) {
        super.setChatInfo(chatInfo);
        if (chatInfo == null) {
            return;
        }

        if (chatInfo.getType() == V2TIMConversation.V2TIM_C2C) {
            isGroup = false;
        } else {
            isGroup = true;
        }

        if (isGroup) {
            mGroupChatManager = GroupChatManagerKit.getInstance();
            mGroupChatManager.setGroupHandler(this);
            GroupInfo groupInfo = new GroupInfo();
            groupInfo.setId(chatInfo.getId());
            groupInfo.setChatName(chatInfo.getChatName());
            mGroupChatManager.setCurrentChatInfo(groupInfo);
            mGroupInfo = groupInfo;
            loadChatMessages(null);
            loadApplyList();
            getTitleBar().getRightIcon().setImageResource(R.mipmap.icon_chat_option_more);
            getTitleBar().getRightIcon().setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(getContext(), R.color.white)));

            getTitleBar().setOnRightClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mGroupInfo != null) {
                        Intent intent = new Intent(getContext(), GroupInfoActivity.class);
                        intent.putExtra(TUIKitConstants.Group.GROUP_ID, mGroupInfo.getId());
                        getContext().startActivity(intent);
                    } else {
                        ToastUtil.toastLongMessage("请稍后再试试~");
                    }
                }
            });
            mGroupApplyLayout.setOnNoticeClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getContext(), GroupApplyManagerActivity.class);
                    intent.putExtra(TUIKitConstants.Group.GROUP_INFO, mGroupInfo);
                    getContext().startActivity(intent);
                }
            });
        } else {
            getTitleBar().getRightIcon().setImageResource(R.mipmap.icon_chat_option_more);
            getTitleBar().getRightIcon().setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(getContext(), R.color.white)));
            mC2CChatManager = C2CChatManagerKit.getInstance();
            mC2CChatManager.setCurrentChatInfo(chatInfo);
            loadChatMessages(null);
            getTitleBar().setOnRightClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showMoreOptionDialog();
                }
            });
            if (chatInfo.getId().equals(Constants.IM_MSG_ADMIN)||chatInfo.getId().equals("administrator"))
                getTitleBar().getRightIcon().setVisibility(GONE);
        }


    }

    /**
     * 更多操作弹窗
     */
    private void showMoreOptionDialog() {
        if (getChatInfo() == null)
            return;
        final String mToUid = getChatInfo().getId();

        TkHttpUtil.INSTANCE.getUserRelation(mToUid, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 0 && StringUtil.isNotEmpty(info)){
                    ImRelationBean bean = Gson2Util.fromJson(info, ImRelationBean.class);

                    List<Integer> list = new ArrayList<>();
                    list.add(R.string.im_chat_bg);
                    list.add(R.string.to_user_home);
                    list.add("1".equals(bean.isAttention()) ? R.string.following : R.string.follow);
                    list.add(R.string.report);
                    list.add("1".equals(bean.isBlack()) ? R.string.black_ing : R.string.black);

                    DialogUitl.showStringArrayDialog(getContext(), list.toArray(new Integer[list.size()]), true,
                            new DialogUitl.StringArrayDialogCallback() {
                                @Override
                                public void onItemClick(String text, int tag) {
                                    if (tag == R.string.to_user_home) {
                                        RouteUtil.forwardUserHome(mToUid);
                                    } else if (tag == R.string.black_ing || tag == R.string.black) {
                                        CommonHttpUtil.setBlack(mToUid);
                                    } else if (tag == R.string.following || tag == R.string.follow) {
                                        CommonHttpUtil.setAttention(mToUid, null);
                                    } else if (tag == R.string.report) {
                                        RouteUtil.forwardReport(1, mToUid);
                                    }else if (tag == R.string.im_chat_bg) {
                                        changeBg();
                                    }
                                }
                            });

                }
            }
        });

    }

    private void changeBg(){
        UploadAvatarUtil.instance.editAvatar((Activity) getContext(), false, new CommonCallback<String>() {
            @Override
            public void callback(String bean) {
                KLog.i("changeGroupImgBg", bean);
                if (StringUtil.isNotEmpty(bean))
                   TkHttpUtil.INSTANCE.setIMChatBg(CommonAppConfig.getInstance().getUid(), bean, new HttpCallback() {
                       @Override
                       public void onSuccess(int code, String msg, String info) {
                           if (code==0){
                               CommonAppConfig.getInstance().clearChatBg();
                               EventBus.getDefault().post(new ChatBgEvent(true));
                           }else {
                               ToastUtil.toastShortMessage(msg);
                           }
                       }
                   });
                else
                    ToastUtil.toastLongMessage("上传失败");
            }
        });
    }


    @Override
    public ChatManagerKit getChatManager() {
        if (isGroup) {
            return mGroupChatManager;
        } else {
            return mC2CChatManager;
        }
    }

    private void loadApplyList() {
        mGroupChatManager.getProvider().loadGroupApplies(new IUIKitCallBack() {
            @Override
            public void onSuccess(Object data) {
                List<GroupApplyInfo> applies = (List<GroupApplyInfo>) data;
                if (applies != null && applies.size() > 0) {
                    mGroupApplyLayout.getContent().setText(getContext().getString(R.string.group_apply_tips, applies.size()));
                    mGroupApplyLayout.setVisibility(VISIBLE);
                }
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                ToastUtil.toastLongMessage("loadApplyList onError: " + errMsg);
            }
        });
    }

    @Override
    public void onGroupForceExit() {
        if (getContext() instanceof Activity) {
            ((Activity) getContext()).finish();
        }
    }

    @Override
    public void onGroupNameChanged(String newName) {
        getTitleBar().setTitle(newName, TitleBarLayout.POSITION.MIDDLE);
    }

    @Override
    public void onApplied(int size) {
        if (size == 0) {
            mGroupApplyLayout.setVisibility(GONE);
        } else {
            mGroupApplyLayout.getContent().setText(getContext().getString(R.string.group_apply_tips, size));
            mGroupApplyLayout.setVisibility(VISIBLE);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        TkHttpUtil.cancel(TkHttpConst.GET_RELATION);
        super.onDetachedFromWindow();
    }
}
